package cn.anc.aonicardv;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.webkit.WebView;

import com.danikula.videocache.HttpProxyCacheServer;
import com.ecarx.sdk.device.DeviceAPI;

import java.io.File;
import java.util.Locale;

import androidx.multidex.MultiDex;
import cn.anc.aonicardv.util.AppUtils;
import cn.anc.aonicardv.util.DataClearManager;
import cn.anc.aonicardv.util.DeviceInfo;
import cn.anc.aonicardv.util.LanguageConstants;
import cn.anc.aonicardv.util.LogUtil;
import cn.anc.aonicardv.util.NetUtils;
import cn.anc.aonicardv.util.SpUtils;
import cn.anc.aonicardv.util.StringUtils;
import cn.anc.aonicardv.util.WiFiUtil;
import cn.anc.aonicardv.util.ui.CarSettingGuiHandler;
import cn.anc.httpcontrolutil.CarControl;
import cn.anc.httpcontrolutil.CarControlSettings;
import cn.anc.httpcontrolutil.cache.CacheManager;

/**
 * Created by yangdai on 2017/5/16.
 */

public class MyApplication extends Application {
    public static boolean isAutoConnectRecorder;
    public static boolean isFirstLocation;
    public static boolean isOpenRealTimeTraffic;
    public static int typeMap;
    public static String wifiSSID;
    public static String wifiPassword;
    public static boolean needAutoConnect = false;


    private static Application mContext;
    public static String IPHeader;
    public static String IP;


    //增加int（可扩展）切换前后路控制，默认为正常的前路
    public static int RtspSwitch = 0;
    public static boolean isCheckUpdate = true;
    /**
     * 当前Acitity个数
     */
    private int activityAount = 0;


    private static android.os.Handler mMainThreadHandler;
    private static Looper mMainThreadLooper;
    private static Thread mMainThread;
    private static int mMainThreadId;


    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        mMainThreadHandler = new android.os.Handler();
        mMainThreadLooper = getMainLooper();
        mMainThread = Thread.currentThread();
        mMainThreadId = android.os.Process.myTid();
        registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
        initWebView();
        DeviceInfo.init(this);
        init(this);
        initECarXAPI(this);

    }

    /**
     * OpenAPI的Device模块
     */
    private DeviceAPI mDeviceAPI;
    private void initECarXAPI(Context context) {

        try{
            mDeviceAPI = DeviceAPI.get(context);
            if (mDeviceAPI == null) {
                StringUtils.printLog("eCarXAPIBase init","null");
                return;
            }
            /*
             * 服务初始化，根据回调接口onAPIReady状态值判断服务是否可用
             * @param b true 服务已初始化完成，false 服务未初始化
             * */
            mDeviceAPI.init(context, b -> {

                LogUtil.e("llcTest0210","------mDeviceAPI-------init-:"+b);

                SpUtils.putBoolean(Constant.SpKeyParam.APP_ECARX_API_LOG, b);
            });
        }catch(Throwable ignore){
            //ignore
        }



    }

    /**
     * 获取主线程Handler
     *
     * @return the mMainThreadHandler
     */
    public static android.os.Handler getMainThreadHandler() {
        return mMainThreadHandler;
    }

    /**
     * 获取主线程轮询器
     *
     * @return the mMainThreadLooper
     */
    public static Looper getMainThreadLooper() {
        return mMainThreadLooper;
    }

    /**
     * 获取主线程
     *
     * @return the mMainThread
     */
    public static Thread getMainThread() {
        return mMainThread;
    }

    /**
     * 获取主线程ID
     *
     * @return the mMainThreadId
     */
    public static int getMainThreadId() {
        return mMainThreadId;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        //重写attachBaseContext方法，开启分包，使4.4兼容FileProvider
        MultiDex.install(this);
    }

    public static void init(Context context) {

        CarControlSettings.setSetSettingItemGuiResource(CarSettingGuiHandler.carSettingGuiResourceHandler);
        initSetting(context);
//        CrashHandler.getInstance().init(context);
        initLanguage();
        initUnit();
        initClearCache();
    }

    public static void exit() {
        System.exit(0);
    }

    public static long lastClearCacheTime;
    private static final int ONE_WEEK_TOTAL_MILLIS = 604800000;

    //处理Android7（N）webview导致应用内语言失效的问题
    private void initWebView() {
        new WebView(this).destroy();
    }

    private static void initClearCache() {
        SpUtils.putString(Constant.SpKeyParam.APP_LOG, "");
        lastClearCacheTime = SpUtils.getLong(Constant.SpKeyParam.LAST_CLEAR_CACHE_TIME, 0);
        if (lastClearCacheTime == 0) {
            SpUtils.putLong(Constant.SpKeyParam.LAST_CLEAR_CACHE_TIME, System.currentTimeMillis());
        } else if (System.currentTimeMillis() - lastClearCacheTime >= ONE_WEEK_TOTAL_MILLIS) {
            File file = new File(CacheManager.CACHE_ROOT_DIR);
            DataClearManager.deleteFolderFile(file.getAbsolutePath(), true);
            SpUtils.putLong(Constant.SpKeyParam.LAST_CLEAR_CACHE_TIME, System.currentTimeMillis());
        }
    }


    private static void initUnit() {
        try {
            int tmpTypeUnit = SpUtils.getInt(Constant.SpKeyParam.SPEED_UINT, -1);
            //初始化
            if (tmpTypeUnit != 0 || tmpTypeUnit != 1) {
                SpUtils.putInt(Constant.SpKeyParam.SPEED_UINT, Configs.DEFUTL_SHOW_UNIT);
            }
        } catch (Exception e) {
            SpUtils.putInt(Constant.SpKeyParam.SPEED_UINT, Configs.DEFUTL_SHOW_UNIT);
        }
    }

    private static void initLanguage() {
        String mLanguage = SpUtils.getString(Constant.SpKeyParam.APP_LANUAGE, null);
        boolean IsUserSettingLanuage = SpUtils.getBoolean(Constant.SpKeyParam.IS_USER_SETTING_LANUAGE, false);
        if (TextUtils.isEmpty(mLanguage) || !IsUserSettingLanuage) {
            Locale l = Locale.getDefault();
            //当前系统语言
            if (Configs.DEFUTL_LANGUAGES.contains(l.getLanguage() + ",")) {
                SpUtils.putString(Constant.SpKeyParam.APP_LANUAGE, l.getLanguage());
            } else {
                SpUtils.putString(Constant.SpKeyParam.APP_LANUAGE, Configs.DEFUTL_LANGUAGE);
            }
        } else {
            //兼容以前设置版本   请注意：国际化app请勿在代码中添加自定义文本，此次为了兼容以前安装过的app
            if (mLanguage.equals("简体中文")) {
                SpUtils.putString(Constant.SpKeyParam.APP_LANUAGE, LanguageConstants.SIMPLIFIED_CHINESE);
            }
            if (mLanguage.equals("English")) {
                SpUtils.putString(Constant.SpKeyParam.APP_LANUAGE, LanguageConstants.ENGLISH);
            }
        }

        String mSelectLanguage = SpUtils.getString(Constant.SpKeyParam.APP_LANUAGE, Configs.DEFUTL_LANGUAGE);
        AppUtils.updateAppLanguage(mContext, new Locale(mSelectLanguage));

    }


    private static void initSetting(Context context) {
        isAutoConnectRecorder = SpUtils.getBoolean(Constant.SpKeyParam.AUTO_CONNECT_RECORDER, true);
        isFirstLocation = SpUtils.getBoolean(Constant.SpKeyParam.IS_FIRST_LOCATION, true);
        isOpenRealTimeTraffic = SpUtils.getBoolean(Constant.SpKeyParam.IS_OPEN_REAL_TIME_TRAFFIC, true);
    }

    public static Application getInstance() {
        return mContext;
    }


    private HttpProxyCacheServer proxy;

    public static HttpProxyCacheServer getProxy(Context context) {
        MyApplication app = (MyApplication) context.getApplicationContext();
        return app.proxy == null ? (app.proxy = app.newProxy()) : app.proxy;
    }

    private HttpProxyCacheServer newProxy() {
        return new HttpProxyCacheServer.Builder(this).maxCacheFilesCount(1).build();
    }

    /**
     * Activity 生命周期监听，用于监控app前后台状态切换
     */
    ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        }

        @Override
        public void onActivityStarted(Activity activity) {
            activityAount++;
            if (activityAount == 1) {
//                if (!NetUtils.isConnectedDevices(mContext)) {
//                    WiFiUtil.getInstance(mContext).openWifi();
//                }

            }
        }

        @Override
        public void onActivityResumed(Activity activity) {
        }

        @Override
        public void onActivityPaused(Activity activity) {
        }

        @Override
        public void onActivityStopped(Activity activity) {
            activityAount--;
            if (activityAount == 0) {
                needAutoConnect = true;
                //发送断连指令,并断开APP与记录仪心跳
                if (CarControl.IsConnected.get()) {
                    CarControl.IsConnected.set(false);
                    CarControl.HeartBeatStop();
                }

                if (NetUtils.isConnectedDevices(mContext)) {
                    WiFiUtil.getInstance(mContext).closeWifi();
                }

            }
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
        }
    };


}
